package com.itheima.servlet;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Keyword;
import com.itheima.service.KeywordService;
import com.itheima.service.impl.KeywrodServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/queryServlet")
public class QueryServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理请求乱码问题，获取前端传来的数据
        request.setCharacterEncoding("utf-8");
        String keyword = request.getParameter("word");
        //创建KeywordService对象调用查询方法
        KeywordService keywordService = new KeywrodServiceImpl();
        List<Keyword> list = keywordService.find(keyword);
        //处理响应乱码
        response.setContentType("text/html;charset=utf-8");
        //将数据库查到的数据转化成Json字符串，并传给后端
        String str = JSON.toJSONString(list);
        response.getWriter().print(str);


    }
}